<?PHP

if(isset($_POST['action']) && $_POST['action'] == 'update_OP_layout_selector'){
	if(check_admin_referer('op_layout_updatelayouts') && current_user_can('manage_options')){
		$new_layout = array_diff_key($_POST,array('action'=>'','Submit'=>'','_wpnonce'=>'','_wp_http_referer'=>''));

		// Need to filter out stray sidebar widgets stored in db
		$layout_diff = array();
		$layouts = array();

		foreach($new_layout as $k => $v){
			foreach($v as $n){
				$layout_diff[$k.'-'.$n] = '';
			}
		}

		// Remove stray widgets
		$current_widgets = get_option('sidebars_widgets');

		if(is_array($current_widgets)){
			$new_widgets = array_intersect_key($current_widgets,$layout_diff);
			$new_widgets['array_version'] = $current_widgets['array_version'];


			update_option('sidebars_widgets',$new_widgets);
		}
		// Update layout
		update_option('op_layout',$new_layout);
	}
}

global $layout_selector;

class OP_Layout_Selector_Interface{
	function layout_selector(){
		global $layout_selector;
		$layout_selector = new OP_Layout_Selector();
		$layout_selector->render_selector();
	}
	
	function ajax_build_column(){
		global $layout_selector;
		$layout_selector = new OP_Layout_Selector();
		$layout = attribute_escape($_POST['layout']);
		$toid = attribute_escape($_POST['toid']);
		echo $layout_selector->build_column($layout,$toid,ucfirst($toid));
	}
	
	function ajax_customize(){
		global $layout_selector;
		$layout_selector = new OP_Layout_Selector();
		$default = explode(',',attribute_escape($_POST['default']));
		$layout_selector->override_default($default);
		
		$type = attribute_escape($_POST['type']);
		$type_class = $type == '' ? '' : $type.'_';
		$type_title = $type == '' ? '' : ucfirst($type).': ';
		$layout_title = attribute_escape($_POST['layout']);
		
		echo '<div class="op_layout_wrapper">',
 			'<h3>'.$type_title.ucwords($layout_title).'<a class="togbox">+</a></h3>', // show title
 			'<div class="inside">',
	 		'<div class="op_layout" id="op_layout_'.$type_class.$layout_title.'">',
			$layout_selector->build_layout(attribute_escape($_POST['layout']),TRUE,$type),
 			'</div>',
	 		'</div><div style="clear:both"></div></div>';

	}
	
	function ajax_save_state(){
		$layouts = explode(',',attribute_escape($_POST['layouts']));
		if(!get_option('op_layout_uistate')){
			add_option('op_layout_uistate',$layouts);
		}
		update_option('op_layout_uistate',$layouts);
	}
}

	
class OP_Layout_Selector{
	var $default, $layouts, $footer, $uistate;
	
	function OP_Layout_Selector(){
		if(!get_option('op_layout')){
			add_option('op_layout',array('default'=>array('main','sidebar1'),'footer'=>array('column1','column2','column3')));
		}
		$op_layout = get_option('op_layout');

		$this->layouts = array_diff_key($op_layout,array('default'=>'','footer'=>''));
		$this->default = $op_layout['default'] ? $op_layout['default'] : array('main','sidebar1');
		$this->footer = $op_layout['footer'] ? $op_layout['footer'] : array('column1','column2','column3');

		if(!get_option('op_layout_uistate')){
			add_option('op_layout_uistate',array());
		}
		$this->uistate = get_option('op_layout_uistate');
		
		call_user_func_array('uksort', array(&$this->layouts, array(&$this,'sort_ui_state')));
	}
	
	function sort_ui_state($a,$b){
		if(in_array($a,$this->uistate)){

			return array_search($a,$this->uistate) > array_search($b,$this->uistate) ? 1 : -1;
		}
		else return 0;
	}
			
	function add_styles(){
		$url = get_bloginfo('template_directory').'/op/admin/';
		wp_register_style('oplayoutselector',$url.'styles/layout_selector.css');
		wp_enqueue_style('oplayoutselector');
		wp_register_script('oplayoutselectorjs', $url.'scripts/layout_selector.js',array('jquery','jquery-ui-sortable'));
		wp_enqueue_script('oplayoutselectorjs');
	}

	function build_column($layout,$name,$title,$type=''){
		ob_start();
		$remove_link = $name == 'main' ? '' : '<a class="remove_column" href="#">X</a>';
		$type = $type == '' ? '' : $type.'_';
		echo <<<EOS
		<div class="layout_column" column="{$layout}_{$name}">
			<div class="column_wrap">
				<span class="controls">$remove_link</span>
				<h4>$title</h4>
				<input type="hidden" value="$name" name="{$type}{$layout}[]">
			</div>
		</div>
EOS;
		return ob_get_clean();
	}
	
	function build_layout($layout,$usedefault=FALSE,$type=''){
		$typeidx = $type == '' ? '' : $type.'_';
		if(!$this->layouts[$typeidx.$layout] || $usedefault){ // if not customized, use default
			$columns = $this->default;
		}
		else{ 
			$columns = $this->layouts[$typeidx.$layout];
		}
		
		ob_start();
		echo '<ul class="layout_options">',
			'<li class="add_sidebars">',
				'<ul>',
					'<input value="sidebar1" type="checkbox"';
					echo in_array('sidebar1',$columns) ? 'CHECKED' : '';
					echo '> Use Sidebar 1<br/>',
						'<input value="sidebar2" type="checkbox"';
					echo in_array('sidebar2',$columns) ? 'CHECKED' : '';
					echo '> Use Sidebar 2',
				'</ul>',
			'</li>',
			'</ul>';
		
			echo '<div class="layout_builder">';
		
		foreach($columns as $column){
			echo $this->build_column($layout, $column, ucfirst($column),$type);
		}
		echo '</div>';
		
		echo '<a href="#" onclick="return false" class="remove_custom_link">- Remove Customization</a>';
		return ob_get_clean();
	}

	function render_selector(){
		require_once(ABSPATH . 'wp-admin/includes/widgets.php');
		
		$blog_url = get_bloginfo('wpurl');
		
		$help = <<<EOS
<h3>Forget Templates!  How to use the OnePress Layout Selector!</h3>
<p>OnePress Theme uses dynamically generated layouts to render your website.  In doing such, your site is completely controlled by the widgets you choose to place in WordPress "sidebars."
<p>With this control panel, you can easily adjust the layout of those "sidebars" for each content type on your site.  To customize-- reorder (drag and drop), add, and remove sidebars from the appropriate content layout.</p>
EOS;
		// Begin generate header layout
			echo '<div class="wrap">', 
			$help,
			'<form id="op_layout_form" method="post" action="">',
			'<div style="float:right"><a target="_blank" href="http://onepresscommunity.com/docs/onepress/#admin-layout">Help</a></div>',
			'<div class="op_layout_wrapper">',
			'<h3>Default Layout</h3>',
			'<div class="op_layout">',

			'<ul class="layout_options">',
			'<li class="add_sidebars">',
				'<ul>',
					'<input value="sidebar1" type="checkbox"';
					echo in_array('sidebar1',$this->default) ? 'CHECKED' : '';
					echo '> Use Sidebar 1<br/>',
						'<input value="sidebar2" type="checkbox"';
					echo in_array('sidebar2',$this->default) ? 'CHECKED' : '';
					echo '> Use Sidebar 2',
				'</ul>',
			'</li>',
			'</ul>',
			'<div class="layout_builder" id="default_layout">';
	
		foreach($this->default as $column){
			echo $this->build_column('default', $column, ucfirst($column));
		}
	
		echo '</div>',
			'</div><div style="clear:both"></div>',
			'</div>';
		// End generate header layout
			
		// Begin generate footer layout
		echo '<div class="op_layout_wrapper">',
			'<h3>Footer</h3>',
			'<div class="op_layout">',

			'<ul class="layout_options">',
			'<li class="add_sidebars">',
				'<ul>';
					foreach(range(2,3) as $idx){
						echo '<input value="column'.$idx.'" type="checkbox"';
						echo in_array('column'.$idx,$this->footer) ? 'CHECKED' : '';
						echo '> Use Column '.$idx.'<br/>';
					}
		echo '</ul>',
			'</li>',
			'</ul>',
			
			'<div class="layout_builder" id="default_layout">';
	
		foreach($this->footer as $column){
			echo $this->build_column('footer', $column, ucfirst($column));
		}
	
		echo '</div>',
			'</div><div style="clear:both"></div></div>';
		// End generate footer layout
		
		/** Display extra layouts **/	
		$customizable = '<div id="customizable_layouts">';
		foreach(array_keys($this->layouts) as $layout_title){
			$old_title = $layout_title;
			$layout_title = explode('_',$layout_title);
			if($layout_title[0] != $old_title){
				$type = $layout_title[0];
				$layout_title = $layout_title[1];
			}
			else{
				$layout_title = $old_title;
				$type = '';
			}

			$type_title = $type == '' ? '' : ucfirst($type).': ';
			$type_class = $type == '' ? '' : $type.'_';
			
 			$customizable .= '<div class="op_layout_wrapper">';
			$customizable .= '<h3>'.$type_title.ucfirst($layout_title).'<a class="togbox">+</a></h3>'; // show title
 			$customizable .= '<div class="inside">';
			$customizable .= '<div class="op_layout" id="op_layout_'.$type_class.$layout_title.'">';
			$customizable .= $this->build_layout($layout_title,FALSE,$type);
			$customizable .= '</div>';
 			
 			$customizable .= '</div><div style="clear:both"></div></div>';
		}
		
		// =========================================
		// = Display drop down control for layouts =
		// =========================================
		global $wpdb;
		$result = $wpdb->get_results("SELECT t.term_id,t.name,t.slug, tt.taxonomy as type from $wpdb->terms t INNER JOIN $wpdb->term_taxonomy tt ON t.term_id=tt.term_id WHERE tt.taxonomy IN('category','post_tag')");
		$category = array('<option></option>');
		$post_tag = array('<option></option>');
		foreach($result as $term){
			$term_pre = $term->type == 'category' ? 'category' : 'tag'; // we save as category_ and tag_, WP uses post_tag internally
			if(array_key_exists($term_pre.'_'.$term->slug,$this->layouts)) continue;
			${$term->type}[] = '<option value="'.$term->slug.'">'.$term->name.'</option>';
		}

		$pages = array('<option></option>');
		$result = $wpdb->get_results("SELECT post_title AS name, post_name AS slug FROM $wpdb->posts w WHERE post_type='page' AND post_status='publish'");
		foreach($result as $page){
			if(array_key_exists('page_'.$page->slug,$this->layouts)) continue;
			$pages[] = '<option value="'.$page->slug.'">'.$page->name.'</option>';
		}
		
		$control = '<div id="customize_layout_control">';
		$control .= '<label>Choose Layout to Customize</label> <select><option></option>';
		
		
		// define default control options for "customize layout" dropdown
		$control_options = array('home','single','page','category','tag','search','archive','author');
		
		// figure out which extra options should be available
		$extra_options = array();
		if(count($category) > 1) $extra_options[] = 'category name';
		if(count($post_tag) > 1) $extra_options[] = 'tag name';
		if(count($pages) > 1) $extra_options[] = 'page title';

		// add rest of control options for dropdown
		// use array_diff to get the difference between defaults and current layouts (this is how we filter out layouts that are already customized)		
		$control_options = array_merge(array_diff($control_options, array_keys($this->layouts)),$extra_options);
		sort($control_options);
		foreach($control_options as $option){
			$control .= '<option value='.str_replace(' ','-',$option).'>'.ucwords($option).'</option>';	
		}
		
		
		$category = '<select id="layout_control_category" style="display:none">'.implode('',$category) . '</select>';
		$post_tag = '<select id="layout_control_tag" style="display:none">'. implode('',$post_tag) . '</select>';
		$pages = '<select id="layout_control_page" style="display:none">' . implode('',$pages) . '</select>';
		
		$control .= '</select>';
		$control .= $category.$post_tag.$pages; // add aux dropdowns
		$control .= '</div>';
		
		echo $control;
		
		// End display control for layouts
		
		//
		// If using static page for front page, notify them to use Home here.
		if(get_option('show_on_front') == 'page'){
			echo '<p><i><b>Attention: </b>A static page is currently set to display as the front page for your site.  To customize the front page, choose "Page Title" followed by the name of the page. To customize the posts page, edit "<b>Home</b>" rather than the individual page in order for changes to be effective.</i></p>';
		}
		
		echo $customizable;
		echo '</div>';
		wp_nonce_field('op_layout_updatelayouts');
		echo '<input type="hidden" name="action" value="update_OP_layout_selector" />';
	
		echo'<p class="submit"><input type="submit" name="Submit" value="';
		_e('Save Changes');
		echo '" /></p></div>',
		    '</div>',
			'</form>',
			'</div>';
			
	}
	
	function override_default($default){
		$this->default = $default;
	}
}

?>